//
//  WLMUserAccountViewModel.swift
//  WeiBo
//
//  Created by Eric on 2017-01-07.
//  Copyright © 2017 Eric. All rights reserved.
//

import UIKit

private let cacheAccountPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")

class WLMUserAccountViewModel: NSObject {

    //设计单例对象
    static let shared: WLMUserAccountViewModel = WLMUserAccountViewModel()
    
    //处理数据
    var account : WLMUserAccount?
    
    var avatarURL: URL? {
        return URL(string: account?.avatar_large ?? "")
    }
    
    //定义token属性
    var access_token: String? {
        return account?.access_token
    }
    
    override init() {
        super.init()
        //给userAccount赋值
        self.account = self.loadUserAccount()
    }
    
    //判断用户是否登录
    var userLogin: Bool {
        if account?.access_token != nil && isExpires == false {
            return true
        }
        return false
    }
    
    //判断token是否过期
    var isExpires: Bool {
        if account?.expires_date?.compare(Date()) == .orderedDescending {
            //满足降序,没过期
            return false
        }
        return true
    }
    
    //视图模型,网络请求,通过code获取令牌
    func loadAccessToken(code: String, finished: @escaping (Bool)->()) {
        //请求接口获取令牌
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let dict = ["client_id" : client_id,
                    "client_secret" : client_secret,
                    "code" : code,
                    "grant_type" : "authorization_code",
                    "redirect_uri" : redirect_uri]
        
        //请求接口
        WLMNetworkTools.sharedManager.request(method: .POST, URLString: urlString, parameters: dict) { (resp, error) in
            if error != nil {
                //执行闭包
                finished(false)
                return
            }
            //请求成功,通过令牌请求用户信息
            self.loadUserInfo(dict: resp as! [String : Any], loadUserInfoFinished: finished)
            
        }
    }
    
    //通过令牌请求用户信息
    private func loadUserInfo(dict: [String : Any], loadUserInfoFinished: @escaping (Bool) -> ()) {
        let access_token = dict["access_token"]!
        let uid = dict["uid"]!
        let parameters = ["access_token" : access_token,
                          "uid" : uid]
        let urlString = "https://api.weibo.com/2/users/show.json"
        WLMNetworkTools.sharedManager.request(method: .GET, URLString: urlString, parameters: parameters) { (respond, error) in
            if error != nil {
                return
            }
            var userInfoDict = respond as! [String : Any]
            
            //授权信息合并到用户信息
            for (key,value) in dict {
                userInfoDict[key] = value
            }
            //转换为模型数据
            let userAccount = WLMUserAccount(dict: userInfoDict)
            //归档
            self.account = userAccount
            self.saveUserAccount(account: userAccount)
            //成功的回调
            loadUserInfoFinished(true)
        }
    }
    
    //存储用户信息
    private func saveUserAccount(account: WLMUserAccount) {
        //归档
        NSKeyedArchiver.archiveRootObject(account, toFile: cacheAccountPath)
    }
    
    //通过解档的方式获取用户信息的模型
    private func loadUserAccount() -> WLMUserAccount? {
        
        if let cacheAccount = NSKeyedUnarchiver.unarchiveObject(withFile: cacheAccountPath) as? WLMUserAccount {
            
            return cacheAccount
        }
        return nil
    }
    
    
    
}





















